package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.BaseContext;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Auther: 宋H
 * @Date: 2022/9/14
 * @Description: com.itheima.controller
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
@Api(tags="购物车信息相关接口")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @GetMapping("/list")
    public R<List<ShoppingCart>> shoppingCartList(ShoppingCart shoppingCart) {
        log.info("查询购物车中...");
        //获取用户id
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);
        return R.success(shoppingCartList);
    }

    /**
     * 添加菜品或者套餐到购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> shoppingCartAdd(@RequestBody ShoppingCart shoppingCart) {
        log.info(shoppingCart.toString());
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId).orderByAsc(ShoppingCart::getCreateTime);

        //判定加入的是否为菜品
        if (shoppingCart.getDishId() != null) {
            lqw.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            lqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart shoppingone = shoppingCartService.getOne(lqw);
        //判定购物车中是否已经存在该用户的菜品或者套餐
        if (shoppingone != null) {
            Integer number = shoppingone.getNumber();
            shoppingone.setNumber(number + 1);
            shoppingCartService.updateById(shoppingone);
        } else {
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            shoppingone=shoppingCart;
        }

        return R.success(shoppingone);
    }

    @DeleteMapping("/clean")
    public R<String> shoppingCartClean(){
        log.info("删除购物车中...");
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(lqw);
        return R.success("成功清除购物车");
    }
}
